var WxParse = require('../../wxParse/wxParse.js');
//获取应用实例
var app = getApp();
const bgMusicAudioContext = wx.getBackgroundAudioManager()
Page({
  data: {
    isShowVideo: false,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    isShowModal: false,
    buyNumber: 1,
    modalOperaType: "",
    cartNumber: 0,
    goodDetail: {},
    chooseGuige: {},
    videoShow:false,
    isShowshare:false,
    intoView:'part1',
    curPart: 'part1',
    curshow:'goodintro',
    isShowposter:false,
    goodType:'good',
    isShowOrdertip:true
  },
  onLoad: function (e) {
    var that = this;
    if (e && e.scene) {
      var scene = decodeURIComponent(e.scene).split('&');
      console.log(scene);
      var secneObj = {};
      for (var i = 0; i < scene.length; i++) {
        var arr = scene[i].split('=');
        var key = arr[0];
        secneObj[key] = arr[1];
      }
      e = secneObj;
    }
    if (e && e.id) {
      var goodId = e.id;
      that.setData({
        goodId: goodId
      })
    }
    if (e && e.laid) {
      var laid = e.laid;
      that.setData({
        laid: laid
      })
    }
    if (e && e.mid) {
      that.setData({
        mid: e.mid
      })
    }
    var res = wx.getSystemInfoSync();
    that.setData({
      winW: res.windowWidth,
      winH: res.windowHeight,
      isShowOrdertip: !that.data.isShowOrdertip
    })
    if (!app.globalData.plumSession) {
      app.plumSessionCallback = plumSession => {
        if (plumSession != '') {
          console.log('查询到登录信息');
          var mid = that.data.mid ? that.data.mid : '';
          var goodId = that.data.goodId;
          app.globalData.requestUrl = app.getNewRequestUrl(mid);
          that.requestDetail(goodId);
          that.requestComment(goodId);
          that.getSlient();
          that.setData({
            isReady:true,
            isHasunionid: app.globalData.isHasunionid,
            haveVcmCard: app.globalData.haveVcmCard
          })
        } else {
          console.log('未查询到登录信息');
          app.wechatSq(that);
        }
      }
    } else {
      var mid = that.data.mid ? that.data.mid : '';
      var goodId = that.data.goodId;
      app.globalData.requestUrl = app.getNewRequestUrl(mid);
      that.requestDetail(goodId);
      that.requestComment(goodId);
      that.getSlient();
      that.setData({
        isReady: true,
        isHasunionid: app.globalData.isHasunionid,
        haveVcmCard: app.globalData.haveVcmCard
      })
    }
  },
  onShow: function () {
    var that = this;
    if (app.globalData.plumSession) {
      that.setData({
        customerService: app.globalData.customerService ? app.globalData.customerService : '',
        isShowFenxiao: app.globalData.isdistrib ? app.globalData.isdistrib : '',
        isapply: app.globalData.isapply ? app.globalData.isapply : '',
        distribOpen: app.globalData.distribOpen ? app.globalData.distribOpen : '',
      })
      app.contactData(that);
      if (app.globalData.requestCartNum>=0){
        that.setData({
          cartNumber: app.globalData.requestCartNum
        })
      }
    }
    that.setData({
      isHasunionid: app.globalData.isHasunionid,
      haveVcmCard: app.globalData.haveVcmCard
    })
    that.getPartH();
  },
  initPage: function(){
    var that = this;
    that.onLoad();
    that.onShow();
  },
  getSlient:function(){
    var that = this;
    var slient = app.globalData.slient ? app.globalData.slient:'';
    that.setData({
      slient: slient
    })
  },
  hideGetuser: function () {
    var that = this;
    that.setData({
      isShowgetuser: false
    })
  },
  // 合成分享图片
  compoundShareImg: function () {
    var that = this;
    var detailInfor = that.data.goodDetail;
    var cover = detailInfor.coverDown;
    // var res = wx.getSystemInfoSync();
    var winW = that.data.winW;
    var canvasW = winW;
    var canvasH = winW * 0.8;
    console.log(canvasW);
    that.setData({
      canvasW: canvasW,
      canvasH: canvasH
    });
    wx.getImageInfo({
      src: cover,
      success(res) {
        console.log(res);
        cover = res.path;
        console.log(cover);
        that.creatShareImg(cover);
      }
    })
  },
  //分享海报合成
  creatShareImg: function (cover) {
    var that = this;
    var detailInfor = that.data.goodDetail;
    var price = detailInfor.price ? detailInfor.price : 0;
    price = detailInfor.shareVipPrice == 1 ? price : detailInfor.noVipPrice;
    var oriprice = detailInfor.oriPrice ? detailInfor.oriPrice : 0;
    var sold = detailInfor.sold ? detailInfor.sold : 0;

    var canvasW = that.data.canvasW;
    var canvasH = that.data.canvasH;
    var shareCanvas = wx.createCanvasContext('share-cover');
    shareCanvas.rect(0, 0, canvasW, canvasH);
    shareCanvas.setFillStyle('#ffffff');
    shareCanvas.fill();
    shareCanvas.drawImage(cover, 0, 0, canvasW, canvasW);

    var leaveH = canvasH * 0.85;
    var conH = canvasH * 0.15;
    shareCanvas.beginPath();
    shareCanvas.rect(0, leaveH, canvasW, conH);
    shareCanvas.setFillStyle('#FB411A');
    shareCanvas.fill();

    shareCanvas.setTextAlign('left');
    shareCanvas.setTextBaseline('middle');
    shareCanvas.setFillStyle('#ffffff');
    shareCanvas.setFontSize(16);
    shareCanvas.fillText('￥', 8, leaveH + conH / 2);
    shareCanvas.setFontSize(22);
    shareCanvas.fillText(price, 24, leaveH + conH / 2);

    if (oriprice > 0) {
     
      var nowPriceW, oriPriceW;
      nowPriceW = (price.toString().length) * 10;
      oriPriceW = (oriprice.toString().length + 1) * 10;
      shareCanvas.setFontSize(16);
      shareCanvas.setFillStyle('rgba(255,255,255,0.8)');
      // var oriPriceW = shareCanvas.measureText('￥' + oriprice);
      shareCanvas.fillText('￥' + oriprice, 37 + nowPriceW, leaveH + conH / 2);
      shareCanvas.moveTo(37 + nowPriceW, leaveH + conH / 2);
      shareCanvas.lineTo(42 + nowPriceW + oriPriceW, leaveH + conH / 2);
      shareCanvas.setStrokeStyle('rgba(255,255,255,0.8)');
      shareCanvas.stroke();
    }

    shareCanvas.beginPath();
    var soldW = canvasW * 0.4;
    var soldX = canvasW * 0.6;
    shareCanvas.beginPath();
    shareCanvas.arc(soldX + conH / 2, leaveH + conH / 2, conH / 2, 0, Math.PI * 2);
    shareCanvas.setFillStyle('#FFC22F');
    shareCanvas.fill();
    shareCanvas.closePath();

    shareCanvas.rect(soldX + conH / 2, leaveH, soldW - conH / 2, conH);
    shareCanvas.setFillStyle('#FFC22F');
    shareCanvas.fill();
    shareCanvas.closePath();

    shareCanvas.setFontSize(18);
    shareCanvas.setTextAlign('center');
    shareCanvas.setTextBaseline('middle');
    shareCanvas.setFillStyle('#ffffff');
    shareCanvas.fillText('已售' + sold + '件', soldX + soldW / 2, leaveH + conH / 2);

    shareCanvas.draw(false, function () {
      setTimeout(function () {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: canvasW,
          height: canvasH,
          canvasId: 'share-cover',
          fileType: 'jpg',
          quality: 1,
          success: function (res) {
            console.log(res.tempFilePath)
            var tempFilePathShow = res.tempFilePath;
            console.log(tempFilePathShow);
            that.setData({
              shareCover: tempFilePathShow
            });
            // wx.hideLoading();
          },
          fail: function () {
            // wx.hideLoading();
          }
        })
      }, 800)
    });
  },
  // 获取用户信息
  getuserInfo: function (e) {
    var that = this;
    if (e.detail.userInfo) {
      var userdata = e.detail;
      console.log(userdata);
      var slient = that.data.slient;
      var again = false;
      if (slient == 0) {
        again = true;
      } 
      app.getuserInfo(that, userdata, again);
    }
  },
  // 客服回复组件间传值
  getreplyData: function (e) {
    console.log(e.detail);
    this.setData(e.detail);
  },
  onReady: function () {
    var that = this;
    that.videoContext = wx.createVideoContext('myVideo');
  },
  onHide: function () {
    this.hideVideo();
  },
  //播放视频
  playVideo: function (e) { 
    var that = this;
    if (app.globalData.isPlay) {
      bgMusicAudioContext.stop();
      app.globalData.curInfoMusicid = '';
      app.globalData.isPlay = false;
      app.globalData.isPlaynew = 'new';
    } 
    that.setData({
      isShowVideo: true
    });
    that.videoContext.play();
  },
  // 关闭视频
  hideVideo: function () {
    var that = this;
    that.setData({
      isShowVideo: false
    })
  },
  requestDetail: function (goodId) {
    var that = this;
    //发起请求，获取列表列表
    var laid = that.data.laid;
    var data = {
      map: 'applet_goods_detail',
      gid: goodId
    };
    if(laid){
      data.laid = laid;
    }
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var goodDetail = res.data.data;
          if (goodDetail.video!=''){
            that.setData({
              video: goodDetail.video,
              videoShow:true,
            })
          }
          var seckill = goodDetail.seckill;
          var chooseGuige = that.data.chooseGuige;
          var stock = goodDetail.stock;

          /** 规格库存判断开始 **/
          if (res.data.data.formatList&&res.data.data.formatList.length==1){   //如果是单规格
              for (let i in res.data.data.formatList[0].value) {
                if (res.data.data.formatValueNew[res.data.data.formatList[0].value[i].name].stock == 0){
                  res.data.data.formatList[0].value[i].noCheck = true;
                }
              }
          }
          /** 规格库存判断结束 **/
          that.setData({
            nogood: 1,
            goodDetail: goodDetail,
            cartNumber: goodDetail.cartNum,
            hasFormat: goodDetail.hasFormat,
            seckill: goodDetail.seckill,
            chooseGuige: {
              stock: stock
            },
            userBuyRecord: goodDetail.userBuyRecord
          })
          if (goodDetail.recommendGoods&&goodDetail.recommendGoods.length>0){
            var recommendGoodslist = app.splitArrData(goodDetail.recommendGoods,3);
            that.setData({
              recommendGoodslist: recommendGoodslist
            })
          }
          if (goodDetail.smallNum > 1) {
            that.setData({
              buyNumber: goodDetail.smallNum
            })
          }
          if (seckill == 1){
            if (seckill == 1) {
              that.setData({
                seckillName: goodDetail.limit.name,
                goodType: 'seckill'
              })
            } else {
              clearInterval(that.data.intervarID);
            }
            that.countDjs();
          }
          var article = that.data.goodDetail.detail;
          // 富文本解析
          WxParse.wxParse('article', 'html', article, that, 5);
          var param = that.data.goodDetail.parameter;
          WxParse.wxParse('param', 'html', param, that, 5);
          that.compoundShareImg();
          that.setData({
            showLive:true
          })
        } else {
          that.setData({
            nogood:0,
            tips: res.data.em
          })
        }
        
      },
      complete: function () {
        wx.hideToast();
      }
    });
  },
  // 收藏商品
  addCollect: function () {
    var that = this;
    var gid = that.data.goodId;
    var goodDetail = that.data.goodDetail;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_mall_goodsCollect',
        gid: gid
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          app.errorTip(that, res.data.data.msg, 2000);
          goodDetail.isCollect = res.data.data.isCollect;
          that.setData({
            goodDetail: goodDetail
          })
        } else {
          console.log(res.data);
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    })
  },
  requestComment: function (goodId) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_goods_comment_list',
        gid: goodId
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          that.setData({
            commentNum: res.data.data.total,
            commentList: res.data.data.list
          })
          console.log(that.data.commentList)
        } else {
          console.log(res.data);
        }
      },
      complete: function () {
        
      }
    });
  },
  toApplyFenxiao: function () {
    wx.navigateTo({
      url: '/pages/becomePartners/becomePartners'
    })
  },
  backShouye: function () {
    app.backHome();
  },
  backCart: function () {
    wx.navigateTo({
      url: '/subpages/mycart/mycart'
    })
  },
  countDjs: function () {
    var that = this;
    // console.log(that.data.goodDetail.limit);
    if (that.data.goodDetail.seckill == 1) {
      var endTime = that.data.goodDetail.limit.endTime * 1000;
      var startTime = that.data.goodDetail.limit.startTime * 1000;
    }
    var curtime = new Date(); //避免页面渲染倒计时的时候出现一秒的延迟。
    var startSpan1 = startTime - curtime;
    var endSpan2 = endTime - curtime;
    if (startSpan1 > 0) {
      that.setData({
        start: '开始',
      })
      that.djs(startSpan1);
    } else {
      that.setData({
        start: '结束',
      })
      that.djs(endSpan2);
    }
    that.data.intervarID = setInterval(function () {
      var nowTime = new Date();
      var startSpan = startTime - nowTime;
      var endSpan = endTime - nowTime;
      if (startSpan > 0) {
        that.setData({
          start: '开始',
        })
        that.djs(startSpan);
      } else {
        that.setData({
          start: '结束',
        })
        that.djs(endSpan);
      }
    }, 1000)
    // }

  },
  djs: function (time) {
    var that = this;
    var leftTime = time;
    that.setData({
      leftTime: leftTime
    })
    if (leftTime > 0) {
      var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
      var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
      var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 
      var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 
      days = days < 10 ? '0' + days : days;
      // console.log(days);
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      that.setData({
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds
      })
      if (days == '00' && hours == '00' && minutes == '00' && seconds == '00') {
        clearInterval(that.data.intervarID);
      }
    } else {
      that.setData({
        days: '00',
        hours: '00',
        minutes: '00',
        seconds: '00',
      })
    }
  },
  chooseGuige: function (e) {
    var that = this;
    var findex = e.currentTarget.dataset.findex;
    var index = e.currentTarget.dataset.index;
    var disabled = e.currentTarget.dataset.disabled;  //是否可以选择
    if (disabled)return;
    var goodDetail = that.data.goodDetail;
    var checkFormat = [];
    for (var i = 0; i < goodDetail.formatList[findex].value.length; i++) {
      if (index==i){
        goodDetail.formatList[findex].value[index].checked = !goodDetail.formatList[findex].value[index].checked;
        if (findex == 0 && goodDetail.formatList[findex].value[index].checked) {
          var curImgformat = goodDetail.formatList[0].value[index]; //当前选择规格的小图展示
          console.log('当前规格索引', findex,index);
          console.log('当前规格图片上一级', goodDetail.formatList[0]);
          console.log('当前规格图片', curImgformat);
          that.setData({
            curImgformat: curImgformat
          })
        }else{
          if (findex == 0){
            that.setData({
              curImgformat: ''
            })
          }  
        }
      }else{
        goodDetail.formatList[findex].value[i].checked = false;
      }
    }
    for (var i = 0; i < goodDetail.formatList.length; i++) {
      for (var j = 0; j < goodDetail.formatList[i].value.length; j++) {
        if (goodDetail.formatList[i].value[j].checked) {
          checkFormat.push(goodDetail.formatList[i].value[j]);
        }
      }
    }
    console.log('选择的规格', checkFormat);
    /** 规格库存判断开始 **/
    for (let k in goodDetail.formatList) {    
      for (let n in goodDetail.formatList[k].value) {
        goodDetail.formatList[k].value[n].noCheck = false
      }
    }

    //存放规格数据的对象
    for(let i in goodDetail.formatValueNew){
      let noStockArr=[]; //没有库存的规格数组
      let formatValueItem = i.split('-');
      // console.log('分割规格名字为数组', formatValueItem);
      switch (checkFormat.length){    //选择的是第几个规格
        case 1:
          if (formatValueItem.indexOf(checkFormat[0].name) != -1 && goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 2) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = ''; 
            noStockArr = formatValueItem;
          } else if (goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 1){
            noStockArr.push(i);
          } else if (formatValueItem.indexOf(checkFormat[0].name) != -1 && goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 3) {
            noStockArr = [];
          } 
          break;
        case 2:
          if ((formatValueItem.indexOf(checkFormat[0].name) != -1 && formatValueItem.indexOf(checkFormat[1].name) != -1) && goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 3) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            noStockArr = formatValueItem;
          } else if ((formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1) && goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 2){
            if (formatValueItem.indexOf(checkFormat[0].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            }
            if (formatValueItem.indexOf(checkFormat[1].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            }
            noStockArr = formatValueItem;
          }
          // console.log(noStockArr);
          break;
        case 3:
          if (goodDetail.formatValueNew[i]['stock'] == 0 && (formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1 || formatValueItem.indexOf(checkFormat[2].name) != -1)) {
            for (let q in checkFormat){
              formatValueItem[formatValueItem.indexOf(checkFormat[q].name)] = '';            
            }
            if (formatValueItem[0] === ''){
              formatValueItem[1] = formatValueItem[2] = formatValueItem[1] + formatValueItem[2]
            }
            if (formatValueItem[1] === '') {
              formatValueItem[0] = formatValueItem[2] = formatValueItem[0] + formatValueItem[2]
            }
            if (formatValueItem[2] === '') {
              formatValueItem[0] = formatValueItem[1] = formatValueItem[0] + formatValueItem[1]
            }
            console.log(formatValueItem);
            noStockArr = formatValueItem
          }
          break;          
      }
      
      //所有规格与没有库存的规格作对比，将库存为0的规格不能选中
      for (let k in goodDetail.formatList) {   
        for (let n in goodDetail.formatList[k].value) {
          // console.log('没有库存的规格', noStockArr);
          if (noStockArr.indexOf(goodDetail.formatList[k].value[n].name)!=-1) {
            goodDetail.formatList[k].value[n].noCheck = true
          }
        }
      }
      
    }
    // 单规格库存判断
    if (goodDetail.formatList.length == 1) {
      for (let i in goodDetail.formatList[0].value) {
        if (goodDetail.formatValueNew[goodDetail.formatList[0].value[i].name].stock == 0) {
          goodDetail.formatList[0].value[i].noCheck = true;
        }
      }
    }
    /** 规格库存判断结束 **/
    console.log(goodDetail.formatList);
    that.setData({
      goodDetail: goodDetail,
      checkFormat: checkFormat
    })
    if (checkFormat.length == goodDetail.formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
        if (i < checkFormat.length - 1) {
          formatName += '-';
        }
      }
      console.log('规格名称',formatName);
      
      console.log(goodDetail.formatValueNew);
      var chooseGuige = goodDetail.formatValueNew[formatName];
      chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    }else{
      that.setData({
        chooseGuige: {
          stock: goodDetail.stock
        }
      })
    }
    var buyNumber = that.data.buyNumber;
    var stock = that.data.chooseGuige.stock;
    if (buyNumber>=stock){
      that.setData({
        buyNumber: stock
      })
    }
  },
  addcart: function (e) {
    var that = this;
    if (app.globalData.slient == 1 || (this.data.isHasunionid == 0 && this.data.haveVcmCard == 1)) {
      return;
    }
    that.setData({
      isShowModal: true,
      modalOperaType: "addcart",
      buyNumber:1
    })
  },
  nowbuy: function () {
    var that = this;
    if (app.globalData.slient == 1 || (this.data.isHasunionid == 0 && this.data.haveVcmCard == 1)) {
      return;
    }
    that.setData({
      isShowModal: true,
      modalOperaType: "buy",
      buyNumber:1
    })
  },
  hideModal: function () {
    var that = this;
    that.setData({
      isShowModal: false
    })
  },
  changeNum: function (e) {
    var that = this;
    var modalOperaType = that.data.modalOperaType;
    var userBuyRecord = that.data.userBuyRecord;
    var type = e.currentTarget.dataset.type;
    var buyNum = parseInt(that.data.buyNumber);
    var stock = that.data.chooseGuige.stock;
    var purchase = that.data.goodDetail.purchase;
    if (type == 'add') {
      if (stock == 0) {
        app.errorTip(that, '商品库存不足', 2000);
      }
      if (buyNum < stock) {
        if (modalOperaType == 'addcart') {
          let curusenum = userBuyRecord.canBuy - userBuyRecord.cartNum; 
          if (buyNum < curusenum) {
            buyNum++;
          } else { 
            app.errorTip(that, '超出限购数量', 2000);
          }
        } else if (modalOperaType == 'buy') {
          if (buyNum < userBuyRecord.canBuy) {
            buyNum++;
          } else {
            app.errorTip(that, '超出限购数量', 2000);
          }
        }
      } else {
        buyNum = stock;
      }
    } else {
      var smallNum = that.data.goodDetail.smallNum > 1 ? that.data.goodDetail.smallNum:1;
      if (buyNum > smallNum) {
        buyNum--;
      } else {
        buyNum = smallNum;
      }
    }

    that.setData({
      buyNumber: buyNum
    })
  },
  numChange: function (e) {
    var that = this;
    var stock = that.data.chooseGuige.stock;
    var val = e.detail.value;
    val = val.replace(/\D/g, '');
    if ((parseInt(val)) > parseInt(stock)) {
      that.setData({
        buyNumber: stock
      })
    } else {
      that.setData({
        buyNumber: val
      })
    }
  },
  confirmAddcart: function (e) {
    var that = this;
    var suid = app.globalData.suid;
    var gid = e.target.dataset.gid;
    var gfid = that.data.chooseGuige.id;
    var num = parseInt(that.data.buyNumber);
    var isFormat = that.data.hasFormat;
    var stock = parseInt(that.data.chooseGuige.stock);
    var data = {
      map: 'applet_add_cart',
      gid: gid,
      gfid: gfid,
      num: num,
      add:1
    }
    if (isFormat && !gfid) {
      app.errorTip(that, '请选择商品规格！', 2000);
      return;
    }
    if (!data.num || data.num <= 0) {
      app.errorTip(that, '请输入正确的商品数量', 2000);
      return;
    }
    console.log("库存数量" + stock);
    console.log("商品数量" + data.num);
    if (data.num > stock) {
      app.errorTip(that, '商品数量超出库存', 2000);
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          wx.showToast({
            title: res.data.data.msg,
            icon: 'success',
            duration: 2000,
          })
          that.hideModal();
          that.setData({
            cartNumber: res.data.data.cartNum
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  nextStep: function () {
    var that = this;
    var gfid = that.data.chooseGuige.id;
    var isFormat = that.data.hasFormat;
    var orderArr = [];
    var orderObj = {};
    orderObj.gid = that.data.goodDetail.id;
    orderObj.gfid = that.data.chooseGuige.id;;
    orderObj.num = parseInt(that.data.buyNumber);
    var stock = parseInt(that.data.chooseGuige.stock);
    orderArr.push(orderObj);
    var data = {};
    data.map = 'applet_order_create';
    data.buys = encodeURI(JSON.stringify(orderArr));
    if (isFormat && !gfid) {
      console.log('请选择商品规格！');
      app.errorTip(that, '请选择商品规格！', 2000);
      return;
    }
    if (!orderObj.num || orderObj.num <= 0) {
      app.errorTip(that, '请输入正确的商品数量', 2000);
      return;
    }
    console.log("库存数量" + stock);
    console.log("商品数量" + orderObj.num);
    if (orderObj.num > stock) {
      app.errorTip(that, '商品数量超出库存', 2000);
      return;
    }
    console.log(data);
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          wx.setStorage({
            key: "submitOrder",
            data: res.data.data,
            success: function (res) {
              console.log(res);
              wx.navigateTo({
                url: '/pages/waitBuyerPay/waitBuyerPay'
              })
            }
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideToast();
      }
    });
  },
  toEvaluateList: function () {
    var that = this;
    var goodid = that.data.goodId;
    wx.navigateTo({
      url: '/pages/evaluateList/evaluateList?goodid=' + goodid
    })
  },
  peiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = e.currentTarget.dataset.imgs;
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  //单张图片预览
  singlePeiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = new Array(e.currentTarget.dataset.imgs);
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  showSharemodal(){
    var pageShare = this.selectComponent('.page-share'), 
    posterData={map:'applet_goods_share_poster',id:this.data.goodId};
    console.log(posterData)
    this.setData({
      posterData:posterData
    })
    pageShare.showSharemodal()
  },
  hideSharemodal(){
    var pageShare = this.selectComponent('.page-share');
    pageShare.hideSharemodal()
  },
 
  toGoodparameter: function (e) {
    var parameter = e.currentTarget.dataset.param;
    wx.setStorage({
      key: "goodParameter",
      data: parameter,
      success:function(){
        wx.navigateTo({
          url: '/subpages/goodParameter/goodParameter',
        })
      }
    })
  },
  // VR视图
  toWebview: function (e) {
    var that = this;
    var vrurl = e.currentTarget.dataset.vrurl;
    var cover = e.currentTarget.dataset.cover;
    var title = e.currentTarget.dataset.title;
    var vrInfo = {
      vrurl: vrurl,
      cover: cover ? cover : '',
      title: title ? title : ''
    }
    wx.setStorage({
      key: 'webviewUrl',
      data: vrInfo,
      success: function () {
        wx.navigateTo({
          url: '/pages/commonView/commonView',
        })
      }
    })
  },
  goodDetail: function (e) {
    var goodId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subpages/goodDetailtwo/goodDetailtwo?id=' + goodId
    })
  },
  jumpPart:function(e){
    var curPart = e.currentTarget.dataset.part;
    this.setData({
      intoView: curPart,
      curPart: curPart
    })
    console.log(this.data.intoView);
  },
  getPartH:function(){
    var that = this;
    var query = wx.createSelectorQuery();
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winH: res.windowHeight
        })
        query.select('#toppart').boundingClientRect(function (rect) {
          if (rect){
            that.setData({
              topPartH: rect.height
            })
          }
        }).exec()
        query.select('#bottompart').boundingClientRect(function (rect) {
          if (rect) {
            that.setData({
              bootomOperaH: rect.height
            })
          }
        }).exec()
      }
    })
    
  },
  goodscroll:function(e){
    var that = this;
    var query = wx.createSelectorQuery();
    query.selectAll('.part-con').boundingClientRect(function (rects) {
      var newRect = [];
      rects.forEach(function (rect) {
        var obj = {
          id : rect.id,
          top : rect.top,
          bottom : rect.bottom,
          height: rect.height
        }
        newRect.push(obj);
      })
      that.getShowpart(newRect);
    }).exec()
  },
  getShowpart: function (newRect){
    var that = this;
    var winH = that.data.winH;
    var topH = that.data.topPartH;
    var bottomH = that.data.bootomOperaH;
    var scrollViewH = winH - topH - bottomH;
    for (var i in newRect){
      var item = newRect[i];
      if (item.bottom-topH<0){
        item.percent = 0;
      }else{
        if (item.bottom - winH>0){
          if (item.top - topH < scrollViewH){
            item.percent = (scrollViewH - (item.top - 40)) / scrollViewH * 100;
          }else{
            item.percent = 0;
          }
        }else{
          if (item.top-topH < 0) {
            if (item.height < scrollViewH) {
              item.percent = 100-1;
            }else{
              item.percent = ((item.bottom - topH) / scrollViewH) * 100;
            }
          } else {
            item.percent = (scrollViewH - (item.top - 40)) / scrollViewH * 100;
          }
        }
      }
    }
    newRect.sort(function (a, b) {
      return b.percent - a.percent;
    })
    that.setData({
      curPart: newRect[0].id
    })
  },
  toggleGoodshow:function(e){
    var that = this;
    var type = e.currentTarget.dataset.type;
    that.setData({
      curshow: type
    })
  },
  //打开折扣卡
  openBuyMenberCard: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    if (type == 0) {
      wx.navigateTo({
        url: '/subpages/memberCard/memberCard'
      })
    } else if (type == 1) {
      wx.navigateTo({
        url: '/subpages/buyMenberCard/buyMenberCard'
      })
    } else if (type == 2) {
      wx.navigateTo({
        url: '/subpages/storeMemberPage/storeMemberPage'
      })
    } else if (type == 3) {
      wx.navigateTo({
        url: '/subpages/walletRecharge/walletRecharge?from=slide'
      })
    }
  },
 
  groupDetail: function (e) {
    var goodid = e.currentTarget.dataset.goodid;
    wx.navigateTo({
      url: '/pages/groupGoodDetail/groupGoodDetail?goodid=' + goodid
    }) 
  },
  toFxposter:function(){
    var id = this.data.goodDetail.id;
    wx.navigateTo({
      url: '/subpages0/distribPoster/distribPoster?id='+id,
    })
  },
  // 优惠券
  toCouponlist: function () {
    wx.navigateTo({
      url: '/subpages/couponList/couponList'
    })
  },
  stoptouchmove:function(e){
  },
  
  onShareAppMessage: function () {
    var that = this; 
    var goodDetail = that.data.goodDetail;
    var mid = app.globalData.userInfo.mid;
    console.log('mid' + app.globalData.userInfo.mid)
    var goodid = that.data.goodId;
    var title = goodDetail.limitShareTitle ? goodDetail.limitShareTitle:goodDetail.name;
    var cover = goodDetail.limitShareImg ? goodDetail.limitShareImg :goodDetail.cover;
    that.hideSharemodal();
    app.getPoint(that);
    return {
      title: title,
      imageUrl: that.data.shareCover ? that.data.shareCover : cover,
      path: '/pages/goodDetail/goodDetail?enterfrom=share&id=' + goodid + '&mid=' + mid
    }
  }
})